<template>
  <div class="wrap">
    <!-- 面包屑 -->
    <div class="bread">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>学员项目管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 搜索框 -->
    <div class="search">
      <template>
        <el-select v-model="value"
                   @change="searchResultChange"
                   clearable
                   filterable
                   remote
                   reserve-keyword
                   placeholder="请输学员姓名 "
                   :remote-method="searchInput">
          <el-option v-for="item in searchResult"
                     :key="item.value"
                     :value="item.name">
          </el-option>
        </el-select>
      </template>

      <el-button icon="el-icon-search"
                 @click="search"></el-button>
      <el-button type="success"
                 @click="dialogVisible=true;dialogEvents='addStudentInfo'">添加信息</el-button>
    </div>
    <!-- 选择器 -->
    <template class="selset">
      <el-form ref="classForm"
               :model="classForm">
        <el-form-item label="选择班级">
          <el-select @change="selectClasses"
                     @click.native="getAllClasses"
                     v-model="classForm.selectedClass"
                     placeholder="请选择班级">
            <el-option label="全部"
                       value="all">
            </el-option>
            <el-option :label="item"
                       :value="item"
                       v-for="item in classes"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </template>
    <!-- 表格 -->
    <template>
      <el-table :data="students"
                :border="true"
                v-loading="studentsTableLoading"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(255,255,255,.5)"
                style="width: 100%">
        <el-table-column label="头像"
                         width="80"
                         height="80"
                         align="center">

          <template slot-scope="scope">
            <img width="100%"
                 height="100%"
                 :src="scope.row.avatarUrl"
                 alt="">
          </template>
        </el-table-column>
        <el-table-column label="姓名"
                         align="center"
                         width="180">
          <template slot-scope="scope">
            <el-popover trigger="hover"
                        placement="bottom">
              <p>创建时间: {{ scope.row.cTime}}</p>
              <p>学历: {{ scope.row.degree }}</p>
              <p>城市: {{ scope.row.city }}</p>
              <div slot="reference"
                   class="name-wrapper">
                <el-tag size="medium">{{ scope.row.name }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="班级"
                         align="center"
                         width="180">
          <template slot-scope="scope">
            <i class="el-icon-s-flag"></i>
            <span style="margin-left: 10px">{{ scope.row.class }}</span>
          </template>
        </el-table-column>
        <el-table-column label="学历"
                         align="center"
                         width="180">
          <template slot-scope="scope">
            <i class="el-icon-tickets"></i>
            <span style="margin-left: 10px">{{ scope.row.degree }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目地址"
                         min-width="80px"
                         align="center">
          <template slot-scope="scope">
            <i class="el-icon-paperclip"></i>
            <a :href="scope.row.productUrl"><span style="margin-left: 10px">{{ scope.row.productUrl }}</span></a>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="180px">
          <template slot-scope="scope">
            <el-button class="el-icon-edit"
                       size="mini"
                       @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button class="el-icon-delete"
                       size="mini"
                       type="danger"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!-- 分页器 -->
    <div class="pagination">
      <el-pagination background
                     layout="prev, pager, next"
                     :page-size="stuCount"
                     :total="stuTotal"
                     @current-change="currentChange">
      </el-pagination>
    </div>
    <!-- dialog窗口 用于添加和编辑的弹窗-->
    <el-dialog title="增加学员项目"
               :visible.sync="dialogVisible">
      <el-form :model="stuForm"
               :rules="stuRules"
               ref="addStuRuleForm">
        <el-form-item label="头像">
          <el-upload class="upload-demo"
                     :limit="1"
                     action="http://106.12.79.128:1901/students/uploadStuAvatar"
                     name="avatar"
                     :show-file-list="showAvatar"
                     :on-success="uploadStuAvatar"
                     list-type="picture">
            <el-button size="small"
                       type="primary">点击上传</el-button>
          </el-upload>
          <el-input v-show="false"
                    v-model="stuForm.avatarUrl"
                    placeholder=""></el-input>
        </el-form-item prop="name">
        <el-form-item label="姓名"
                      prop="name">
          <el-input v-model="stuForm.name"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="项目地址"
                      prop="productUrl">
          <el-input v-model="stuForm.productUrl"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="班级"
                      prop="class">
          <el-input v-model="stuForm.class"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄"
                      prop="age">
          <el-input v-model="stuForm.age"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="城市"
                      prop="city">
          <el-input v-model="stuForm.city"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学历"
                      prop="degree">
          <el-input v-model="stuForm.degree"
                    autocomplete="off"></el-input>
        </el-form-item>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="stuForm.description"
                    autocomplete="off"></el-input>
        </el-form-item>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="confirmClick('addStuRuleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
 <script>
  import { getClasses, getStudents, addStu, delStu, editStuInfo, searchStu } from "@/api"
  export default {
    data() {
      return {
        // 搜索结果数组
        keys: "",
        searchResult: [],
        showAvatar: true,
        studentsTableLoading: false,
        dialogVisible: false,
        stuRules: {
          name: [
            { required: true, message: '请输入名字', trigger: 'blur' },
          ],
          class: [
            { required: true, message: '请输入班级', trigger: 'blur' },
          ],
          degree: [
            { required: true, message: '请输入学历', trigger: 'blur' },
          ],
          city: [
            { required: true, message: '请输入城市', trigger: 'blur' },
          ],
          productUrl: [
            { required: true, message: '请输入项目地址', trigger: 'blur' },
          ],
          age: [
            { required: true, message: '请输入年龄', trigger: 'blur' },
          ]
        },
        classForm: {
          selectedClass: "",
          class: "H51901"
        },
        stuForm: {
          name: "",
          productUrl: "",
          avatarUrl: "",
          class: '',
          age: "",
          city: "",
          degree: "",
          description: ""
        },
        students: [],
        value: "",
        classes: [],
        //用于复用dialogEvent传递的事件名字
        dialogEvents: "addStudentInfo",
        //每页显示几条
        stuCount: 10,
        //总数
        stuTotal: 30
      }
    },
    created() {

    },
    mounted() {
      this.getStuList()
    },
    methods: {
      //获取班级列表
      getAllClasses() {
        //发送请求获取班级列表
        let _this = this;
        getClasses()
          .then(res => {
            if (res.data.state) {
              _this.classes = res.data.data;
            }
          })
      },
      selectClasses() {
        //再次发送请求 获取学员信息 
        let selected = this.classForm.selectedClass
        let query = selected === 'all' ? {
          count: 10
        } : {
            class: selected,
            count: 10
          }
        this.getStuList(query)
      },
      currentChange(page) {
        //默认一页显示10条
        console.log(this.classForm.selectedClass)
        let query = {
          key: this.value,
          count: 10,
          page,
          class: this.classForm.selectedClass
        }
        this.getStuList(query)
      },
      //获取学员信息
      getStuList(query = { count: 10 }) {
        this.studentsTableLoading = true;
        let _this = this;
        getStudents(query)
          .then(res => {
            if (res.data.state) {
              _this.students = res.data.data
              //关闭表格加载动画
              console.log(res.data)
              _this.studentsTableLoading = false;
              //重新给stuTotal赋值
              this.stuTotal = res.data.total
            }
            console.log(res)
          })
      },
      //增加学员信息的方法
      addStudentInfo() {
        //表示表单验证通过
        let data = this.stuForm //获取添加表单里的信息
        console.log(data)
        console.log(data)
        addStu(data)
          .then(res => {
            if (res.data.state) {//表示添加成功
              //让页面刷新 把得到的addstuForm对象unshift到students数组
              this.getStuList()
              //让这个模态框关闭
              this.dialogVisible = false;
              this.$message({
                type: 'success',
                message: '添加成功!'
              });
            }
          })
      },
      //编辑学员信息的方法
      editStudentInfo() {
        let updated = this.stuForm;
        console.log(updated)
        //调用更新的api
        editStuInfo(updated)
          .then(res => {
            if (res.data.state) {
              //关闭dialog框
              this.dialogVisible = false;
              //1强制更新 方法虽好用 但不要滥用哟
              // this.$forceUpdate();

              //2正确的方式
              // let editIndex = this.$store.state.editIndex;
              // let editRow = this.$store.state.editRow
              // this.$set(this.students, editIndex, editRow)
              //3直接重新获取列表
              this.getStuList()
              this.$message({
                type: 'success',
                message: '修改成功!'
              });
            } else {
              this.$message({
                type: 'error',
                message: '你没有做任何修改出错'
              });
            }
          })
      },
      //点击编辑按钮触发的事件
      handleEdit(index, row) {
        this.dialogEvents = 'editStudentInfo'
        this.dialogVisible = true;
        //获取当前行的内容 并且填入其中
        //this.stuForm = row;//此处是浅拷贝 需要变成深拷贝
        let stuForm = JSON.stringify(row)
        console.log(row)
        this.stuForm = JSON.parse(stuForm)
        //把需要更新的index存到vuex 以便于让后续的方法(editStuInfo)dom进行更新
        this.$store.commit('setEditIndex', index)
        this.$store.commit('setEditRow', this.stuForm)
      },
      //点击增加学员信息的确定按钮
      confirmClick(formName) {
        this.$refs[formName].validate((valid) => {
          console.log(valid)
          if (valid) {
            let dialogEventName = this.dialogEvents;
            this[dialogEventName]()
          } else {
            this.$alert('添加学员信息失败', '提示', {
              confirmButtonText: '确定'
            });
          }
        });
      },
      handleDelete(index, row) {
        console.log(111)
        let sId = row.sId;
        //让用户确认一下是否要删除该条信息
        this.$confirm('此操作将永久删除学员, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //D调用删除学员的api
          delStu(sId)
            .then(res => {
              if (res.data.state) {
                //更新dom
                this.students.splice(index, 1)
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
              } else {
                this.$message({
                  type: 'info',
                  message: '该消息已被删除'
                });
              }
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //-----------------------
      uploadStuAvatar(res) {
        this.stuForm.avatarUrl = res.avatarUrl;
        console.log(res)
      },
      // 搜索框输入值发生变化的时候
      searchInput(key) {
        console.log("1111111")
        this.key = key;
        if (!key) {
          return
        } else {
          let query = {
            key,
            count: 10
          }
          searchStu(query)
            .then(res => {
              if (res.data.state) {
                this.searchResult = res.data.data;
                console.log(this.searchResult)
              }
            })
        }
      },
      //搜索框选中某个结果之后
      searchResultChange() {
        if (!this.value) {
          return
        } else {
          let query = {
            key: this.value,
            count: 10
          }
          searchStu(query)
            .then(res => {
              if (res.data.state) {
                this.students = res.data.data
                this.searchResult = [];
                // console.log(res)
                this.key = ""
                this.stuTotal = res.data.total;
              }
            })
        }
      },
      //点击放大镜按钮触发的事件
      search() {
        let query = {
          key: this.key,
          count: 10
        }
        searchStu(query)
          .then(res => {
            if (res.data.state) {
              this.students = res.data.data
              this.searchResult = [];
              //情况key
              this.value = this.key;
              this.key = ""
              this.stuTotal = res.data.total;
            }
          })
      }
    }
  }
  </script>
  <style>
  /* 面包屑样式 */
  .bread .el-breadcrumb {
    padding: 10px;
    border-bottom: 1px solid #e4e4e4;
  }
  /* 搜索样式 */
  .search .el-input__inner {
    min-width: 300px !important;
  }
  /* 选择器样式 */
  .search .el-select {
    margin-top: 30px;
  }
  .el-form .el-form-item {
    margin: 22px 0;
  }
  /* 分页器样式 */
  .pagination .el-pagination {
    margin: 20px 40%;
  }
  /* 表格样式 */
  .el-table__row td .cell {
    height: 40px;
  }
</style>
  
